/*
 * @Author: wjk
 * @Date: 2020-06-29 14:47:37
 * @LastEditors: wjk
 * @LastEditTime: 2020-10-12 16:28:50
 * @description: 碧斯诺兰埋点SDK
 * 文档地址 https://www.tapd.cn/my_worktable?source_user=1395704209&workspace_id=51863674&workitem_type=story&workitem_id=1151863674001002202#&filter_close=true
 * 使用说明 引入SDK之后, 调用track方法即可
 */
// #ifdef H5
import Bridge from '@/plugins/JSBridge'
// #endif

const pType = {
  'h5': 'BIXUAN_H5',
  'mp-weixin': 'BIXUAN_MINI'
}
export const platformType = pType[process.env.VUE_APP_PLATFORM]
const userInfo = uni.getStorageSync('biXuanWorld') || null
const showLogs = false // process.env.NODE_ENV === 'development'
const globalEventName = 'bixuan_event'
let sensor

// 初始化神策SDK
// #ifdef MP-WEIXIN
import saMini from 'sa-sdk-miniprogram'
saMini.setPara({
  server_url: process.env.VUE_APP_SENSOR_URL,
  show_log: showLogs
})
saMini.init()
sensor = saMini
sensor.registerSuperProperties = saMini.registerApp
// #endif

// #ifdef H5
var saJs = require('sa-sdk-javascript')
saJs.init({
  server_url: process.env.VUE_APP_SENSOR_URL,
  is_track_single_page: true,
  show_log: showLogs,
  heatmap: {
    clickmap: 'default',
    scroll_notice_map: 'not_collect'
  }
})
sensor = saJs
sensor.registerSuperProperties = saJs.registerPage
// #endif

class BSNLAnalyticsSDK {
  // 私有属性, 外部引入的SDK
  static #SDK = sensor
  // 事件链
  static #EVENT_LINKS = []
  // 平台
  static platformType = platformType
  // 公共事件名
  static globalEventName = globalEventName
  // 设置神策公共属性
  static registerSuperProperties(properties) {
    this.#SDK.login(properties.uid)
    this.#SDK.setProfile({
      platformType,
      ...properties
    })
    this.#SDK.registerSuperProperties({
      platformType,
      ...properties
    })
  }
  /**
   * @description: 忽略需要打断events_link的event
   * 只需匹配event的前2位即可（即业务+页面）
   * @param {Array} events 需要忽略的事件
   * @return:
   */
  static configIgnoreBreakEventsLinksEvents(events) {
    if (!Array.isArray(events)) return
    this.ignore_break_events_links_events = events || []
  }
  /**
   * @description: 需要重置events_link的events，即碰到该【业务+页面】时，清空events_link
   * 只需匹配event的前2位即可（即业务+页面）
   * @param {Array} events 需要重置events_link的事件
   * @return:
   */

  static configResetEventsLinksEvents(events) {
    if (!Array.isArray(events)) return
    this.reset_events_links_events = events || []
  }
  /**
   * @description: 设置不需要添加到events_link的事件，比如login事件可以不用添加
   * 到events_links具体匹配到一个完整的事件（event）
   * @param {Array} events 需要重置events_link的事件
   * @return:
   */
  static configIgnoreEventsAddedToEventsLinks(events) {
    if (!Array.isArray(events)) return
    this.ignore_events_added_to_events_links = events || []
  }

  /**
   * @description: 调用 track 接口，上报事件，该事件默认不上报event_link
   * @param {String} event 事件名称
   * @param {String} append_extra_key 给event追加一个关键id，用于往回追溯该事件事有关键值可以查询
   * @param {Object} extra_properties 拓展属性
   * @param {Boolean} need_events_link 是否需要上报event_link
   * @return:
   */
  static track(event, append_extra_key = '', extra_properties = {}, need_events_link) {
    if (!event) return
    const data = {
      event_key: append_extra_key ? event + `.${append_extra_key}` : event,
      events_link: '',
      ...extra_properties
    }
    const uploadEventLink = this.updateEventLinks(data.event_key)
    if (need_events_link) {
      data.events_link = uploadEventLink
    }
    // console.log('record_events_link', this.record_events_link)
    // console.log('uploadEventLink', uploadEventLink)
    console.log('last_events_link', this.last_events_link, data)
    // #ifdef H5
    if (Bridge.isInApp) {
      data.last_events_link = this.last_events_link
      Bridge.callHandler({
        type: 'analyticsTrack',
        data: {
          event,
          append_extra_key: String(append_extra_key),
          extra_properties,
          need_events_link,
          last_events_link: this.last_events_link
        }
      })
      return
    }
    // #endif
    return this.#SDK.track(this.globalEventName, data)
  }
  static get EVENT_LINKS() {
    return this.#EVENT_LINKS.join('-->')
  }
  static set EVENT_LINKS(event_links) {
    this.#EVENT_LINKS = event_links.split('-->')
  }
  // 更新EVENT_LINKS
  static updateEventLinks(key) {
    if (this.ignore_events_added_to_events_links) {
      var noAddFlag = false
      for (let index = 0; index < this.ignore_events_added_to_events_links.length; index++) {
        if (key.split('.').slice(0, 2).join('.').includes(this.ignore_events_added_to_events_links[index])) {
          noAddFlag = true
          break
        }
      }
      // console.log('this.ignore_events_added_to_events_links', this.ignore_events_added_to_events_links)
      // if (noAddFlag) return this.EVENT_LINKS
    }
    if (this.reset_events_links_events) {
      var resetFlag = false
      for (let index = 0; index < this.reset_events_links_events.length; index++) {
        if (key.split('.').slice(0, 2).join('.').includes(this.reset_events_links_events[index])) {
          this.#EVENT_LINKS = []
          resetFlag = true
        }
      }
      // console.log('this.reset_events_links_events', this.reset_events_links_events)
    }
    let breakFlag = false
    if (this.ignore_break_events_links_events) {
      for (let index = 0; index < this.ignore_break_events_links_events.length; index++) {
        if (key.includes(this.ignore_break_events_links_events[index])) {
          breakFlag = true
          break
        }
      }
      // console.log('this.ignore_break_events_links_events', breakFlag, this.ignore_break_events_links_events)
    }
    if (breakFlag) {
      this.#EVENT_LINKS.push(key)
      return this.EVENT_LINKS
    } else {
      var tempArr = this.#EVENT_LINKS.concat()
      const index = tempArr.findIndex(item => key.split('.').slice(0, 2).join('.') === item.split('.').slice(0, 2).join('.'))
      // if (index === this.#EVENT_LINKS.length) {
      //   return
      // }
      if (index > -1) {
        tempArr = tempArr.slice(0, index)
      }
      tempArr.push(key)
      if (!noAddFlag && !resetFlag) {
        this.#EVENT_LINKS = tempArr
      }
      return tempArr.join('-->')
    }
  }
  // 最近一次的events_link
  static get record_events_link() {
    const temp = this.#EVENT_LINKS.concat()
    temp.pop()
    return temp.join('-->')
  }
  // 最近一次的events_link
  static get last_events_link() {
    return this.EVENT_LINKS
  }
}

// 初始化时注册一次
BSNLAnalyticsSDK.registerSuperProperties({
  platformType,
  uid: userInfo ? userInfo.uid : sensor.quick('getAnonymousID'),
  mobile: userInfo ? userInfo.mobile : ''
})
// 用例
// BSNLAnalyticsSDK.configResetEventsLinksEvents(['01.100'])
// BSNLAnalyticsSDK.configIgnoreBreakEventsLinksEvents(['01.02'])
// BSNLAnalyticsSDK.configIgnoreEventsAddedToEventsLinks(['01.02'])
// BSNLAnalyticsSDK.track('01.10.01.01') // 活动
// BSNLAnalyticsSDK.track('01.02.01.01') // 商品详情
// BSNLAnalyticsSDK.track('01.02.02.01') // 购物车
// BSNLAnalyticsSDK.track('01.07.01.01') // 商品详情
// BSNLAnalyticsSDK.track('01.02.02.01') // 购物车
// BSNLAnalyticsSDK.track('01.02.01.01') // 商品详情
// BSNLAnalyticsSDK.track('01.07.02.01') // 去支付
// console.log('BSNLAnalyticsSDK', BSNLAnalyticsSDK.EVENT_LINKS)
// console.log('BSNLAnalyticsSDK', BSNLAnalyticsSDK.last_events_link)
export default BSNLAnalyticsSDK
